<!-- OrderDetail.vue - 订单详情页 -->
<template>
  <div class="order-detail-page">
    <!-- 返回按钮 -->
    <div class="back-btn">
      <el-button @click="$router.back()" icon="ArrowLeft">
        返回订单列表
      </el-button>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>

    <!-- 订单详情 -->
    <div v-else-if="order" class="order-detail">
      <!-- 订单状态卡片 -->
      <el-card class="status-card" shadow="hover">
        <div class="status-content">
          <el-icon class="status-icon" :class="`status-${order.status}`">
            <component :is="getStatusIcon(order.status)" />
          </el-icon>
          <div class="status-info">
            <h2 class="status-title">{{ getStatusTitle(order.status) }}</h2>
            <p class="status-desc">{{ getStatusDesc(order.status) }}</p>
          </div>
        </div>
        <el-tag :type="getStatusType(order.status)" size="large" class="status-tag">
          {{ getStatusText(order.status) }}
        </el-tag>
      </el-card>

      <!-- 订单信息 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><Document /></el-icon>
            <span>订单信息</span>
          </div>
        </template>

        <div class="info-row">
          <span class="info-label">订单号：</span>
          <span class="info-value">{{ order.code }}</span>
          <el-button text size="small" @click="copyOrderNo">
            <el-icon><DocumentCopy /></el-icon>
            复制
          </el-button>
        </div>

        <div class="info-row">
          <span class="info-label">创建时间：</span>
          <span class="info-value">{{ formatDate(order.createTime) }}</span>
        </div>

        <div class="info-row" v-if="order.tradeTime">
          <span class="info-label">交易时间：</span>
          <span class="info-value">{{ formatDate(order.tradeTime) }}</span>
        </div>

        <div class="info-row" v-if="order.updateTime && order.updateTime !== order.createTime">
          <span class="info-label">更新时间：</span>
          <span class="info-value">{{ formatDate(order.updateTime) }}</span>
        </div>
      </el-card>

      <!-- 买家信息 -->
      <el-card class="buyer-card" shadow="hover" v-if="order.buyerName">
        <template #header>
          <div class="card-header">
            <el-icon><User /></el-icon>
            <span>买家信息</span>
          </div>
        </template>

        <div class="buyer-info">
          <div class="info-row">
            <span class="info-label">收货人：</span>
            <span class="info-value">{{ order.buyerName }}</span>
          </div>
          <div class="info-row" v-if="order.buyerPhone">
            <span class="info-label">联系电话：</span>
            <span class="info-value">{{ order.buyerPhone }}</span>
          </div>
          <div class="info-row" v-if="order.buyerAddress">
            <span class="info-label">收货地址：</span>
            <span class="info-value">{{ order.buyerAddress }}</span>
          </div>
        </div>
      </el-card>

      <!-- 商品信息 -->
      <el-card class="product-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><ShoppingBag /></el-icon>
            <span>商品信息</span>
          </div>
        </template>

        <div class="product-content">
          <div class="product-image">
            <el-image :src="getImageUrl(order.coverList)" fit="cover">
              <template #error>
                <div class="image-error">
                  <el-icon><PictureFilled /></el-icon>
                </div>
              </template>
            </el-image>
          </div>

          <div class="product-info">
            <h3 class="product-name">{{ order.productName }}</h3>
            <div class="product-meta">
              <el-tag size="small" :type="getOldLevelType(order.oldLevel)">
                {{ getOldLevelText(order.oldLevel) }}
              </el-tag>
            </div>
            <div class="product-price">
              <span>单价：¥{{ order.price }}</span>
              <span>数量：{{ order.quantity }}</span>
            </div>
          </div>

          <div class="product-total">
            <span class="total-label">实付款</span>
            <span class="total-amount">¥{{ order.totalAmount }}</span>
          </div>
        </div>
      </el-card>

      <!-- 操作按钮 -->
      <el-card class="action-card" shadow="hover">
        <div class="action-buttons">
          <!-- 待支付：取消订单、支付订单 -->
          <template v-if="order.status === 'pending'">
            <el-button size="large" @click="handleCancelOrder">
              取消订单
            </el-button>
            <el-button type="primary" size="large" @click="handlePayOrder">
              立即支付
            </el-button>
          </template>

          <!-- 已发货：确认收货 -->
          <template v-if="order.status === 'shipped'">
            <el-button type="success" size="large" @click="handleConfirmOrder">
              确认收货
            </el-button>
          </template>

          <!-- 已完成：再次购买 -->
          <template v-if="order.status === 'delivered'">
            <el-button type="primary" size="large" @click="handleBuyAgain">
              再次购买
            </el-button>
          </template>

        </div>
      </el-card>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-empty description="订单不存在或已被删除">
        <el-button type="primary" @click="$router.push('/gear/buying')">
          返回订单列表
        </el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderAPI } from '@/api'
import {
  ArrowLeft,
  Document,
  DocumentCopy,
  ShoppingBag,
  PictureFilled,
  Clock,
  Wallet,
  Van,
  CircleCheck,
  WarningFilled,
  User
} from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 数据
const order = ref(null)
const loading = ref(false)


// 获取订单详情
const fetchOrderDetail = async () => {
  try {
    loading.value = true
    const orderId = route.params.id
    
    const response = await orderAPI.getOrderDetail(orderId)
    if (response.code === 0) {
      order.value = response.data
      console.log('OrderDetail: 订单详情数据:', order.value)
      console.log('OrderDetail: 商品信息:', {
        productName: order.value.productName,
        price: order.value.price,
        coverList: order.value.coverList,
        oldLevel: order.value.oldLevel
      });
    } else {
      console.error('OrderDetail: 获取订单详情失败:', response)
      ElMessage.error(response.message || '获取订单详情失败')
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    
    // 处理401未授权错误
    if (error.response && error.response.status === 401) {
      console.warn('OrderDetail: 用户未授权，可能是token过期')
      // 不显示错误消息，因为request.js已经处理了token清除
      // 用户会被路由守卫重定向到登录页
    } else {
      ElMessage.error('获取订单详情失败')
    }
  } finally {
    loading.value = false
  }
}

// 复制订单号
const copyOrderNo = () => {
  navigator.clipboard.writeText(order.value.code)
  ElMessage.success('订单号已复制')
}

// 取消订单
const handleCancelOrder = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消该订单吗？',
      '取消订单',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await orderAPI.cancelOrder(order.value.id)
    ElMessage.success('订单已取消')
    order.value.status = 'cancelled'
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }
}

// 支付订单
const handlePayOrder = () => {
  ElMessageBox.alert(
    `<div style="text-align: left; padding: 10px;">
      <p style="font-size: 16px; margin-bottom: 10px;">订单号：<strong>${order.value.code}</strong></p>
      <p style="font-size: 18px; color: #f56c6c; margin-bottom: 10px;">应付金额：<strong>¥${order.value.totalAmount}</strong></p>
      <p style="color: #909399; font-size: 14px;">ℹ️ 当前暂未开通在线支付功能</p>
      <p style="color: #909399; font-size: 14px;">请联系卖家线下交易</p>
    </div>`,
    '支付提示',
    {
      confirmButtonText: '我知道了',
      dangerouslyUseHTMLString: true
    }
  )
}

// 确认收货
const handleConfirmOrder = async () => {
  try {
    await ElMessageBox.confirm(
      '确认已收到商品吗？',
      '确认收货',
      {
        confirmButtonText: '确认收货',
        cancelButtonText: '取消',
        type: 'success'
      }
    )

    await orderAPI.confirmOrder(order.value.id)
    ElMessage.success('确认收货成功')
    order.value.status = 'delivered'
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败')
    }
  }
}

// 再次购买
const handleBuyAgain = () => {
  // 检查订单状态，只有待付款和已取消的订单才能再次购买
  if (order.value && !['pending', 'cancelled'].includes(order.value.status)) {
    ElMessage.warning('该订单状态不允许再次购买')
    return
  }
  
  router.push(`/gear/product/${order.value.productId}`)
}


// 工具函数
const getStatusIcon = (status) => {
  const map = {
    'pending': 'Clock',
    'paid': 'Wallet',
    'shipped': 'Van',
    'delivered': 'CircleCheck',
    'cancelled': 'WarningFilled'
  }
  return map[status] || 'Document'
}

const getStatusTitle = (status) => {
  const map = {
    'pending': '等待买家支付',
    'paid': '等待卖家发货',
    'shipped': '卖家已发货',
    'delivered': '交易成功',
    'cancelled': '交易已取消'
  }
  return map[status] || '未知状态'
}

const getStatusDesc = (status) => {
  const map = {
    'pending': '请尽快完成支付，超时订单将自动取消',
    'paid': '卖家正在准备发货，请耐心等待',
    'shipped': '商品已发出，请注意查收',
    'delivered': '感谢您的购买，期待再次光临',
    'cancelled': '订单已取消，如有疑问请联系客服'
  }
  return map[status] || ''
}

const getStatusText = (status) => {
  const map = {
    'pending': '待支付',
    'paid': '已支付',
    'shipped': '已发货',
    'delivered': '已收货',
    'cancelled': '已取消'
  }
  return map[status] || '未知'
}

const getStatusType = (status) => {
  const map = {
    'pending': 'warning',
    'paid': 'info',
    'shipped': 'primary',
    'delivered': 'success',
    'cancelled': 'info'
  }
  return map[status] || 'info'
}

const getImageUrl = (coverList) => {
  if (!coverList) return ''
  try {
    const list = typeof coverList === 'string' ? JSON.parse(coverList) : coverList
    return Array.isArray(list) ? list[0] : list
  } catch {
    return coverList
  }
}

const getOldLevelText = (level) => {
  const map = {
    1: '很旧', 2: '较旧', 3: '一般', 4: '较新', 5: '全新',
    6: '95新', 7: '95新', 8: '较新', 9: '95新', 10: '全新'
  }
  return map[level] || '未知'
}

const getOldLevelType = (level) => {
  if (level >= 9) return 'success'
  if (level >= 7) return 'info'
  if (level >= 5) return 'warning'
  return 'danger'
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

onMounted(() => {
  fetchOrderDetail()
})
</script>

<style scoped lang="scss">
$primary-color: #409eff;
$danger-color: #f56c6c;
$warning-color: #e6a23c;
$success-color: #67c23a;

.order-detail-page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.back-btn {
  margin-bottom: 20px;
}

.loading-container {
  background: white;
  border-radius: 12px;
  padding: 40px;
}

.order-detail {
  .el-card {
    margin-bottom: 20px;
    border-radius: 12px;
    overflow: hidden;

    .card-header {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }
}

.status-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;

  .status-content {
    display: flex;
    align-items: center;
    gap: 20px;
    margin-bottom: 15px;

    .status-icon {
      font-size: 60px;

      &.status-0 { color: $warning-color; }
      &.status-1 { color: #909399; }
      &.status-2 { color: $primary-color; }
      &.status-3 { color: $success-color; }
      &.status-4 { color: #909399; }
    }

    .status-info {
      .status-title {
        font-size: 24px;
        margin: 0 0 10px 0;
        font-weight: 600;
      }

      .status-desc {
        font-size: 14px;
        margin: 0;
        opacity: 0.9;
      }
    }
  }

  .status-tag {
    background: rgba(255, 255, 255, 0.2);
    border: 2px solid rgba(255, 255, 255, 0.5);
    color: white;
    font-weight: 600;
  }
}

.info-card {
  .info-row {
    display: flex;
    align-items: center;
    padding: 15px 0;
    border-bottom: 1px solid #e4e7ed;

    &:last-child {
      border-bottom: none;
    }

    .info-label {
      font-size: 15px;
      color: #606266;
      width: 120px;
      flex-shrink: 0;
    }

    .info-value {
      font-size: 15px;
      color: #303133;
      flex: 1;
      font-family: monospace;
    }
  }
}

.product-card {
  .product-content {
    display: flex;
    gap: 20px;
    cursor: pointer;
    padding: 10px;
    border-radius: 8px;
    transition: all 0.3s;

    &:hover {
      background: #f5f7fa;
    }

    .product-image {
      width: 120px;
      height: 120px;
      border-radius: 8px;
      overflow: hidden;
      flex-shrink: 0;

      .image-error {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: #f5f7fa;
        color: #909399;
        font-size: 40px;
      }
    }

    .product-info {
      flex: 1;

      .product-name {
        font-size: 18px;
        color: #303133;
        margin: 0 0 10px 0;
        font-weight: 600;
      }

      .product-meta {
        margin-bottom: 10px;
      }

      .product-price {
        display: flex;
        gap: 20px;
        font-size: 14px;
        color: #606266;
      }
    }

    .product-total {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      justify-content: center;

      .total-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 5px;
      }

      .total-amount {
        font-size: 24px;
        color: $danger-color;
        font-weight: 700;
      }
    }
  }
}

.action-card {
  .action-buttons {
    display: flex;
    gap: 15px;
    justify-content: flex-end;

    .el-button {
      min-width: 120px;
    }
  }
}

.error-container {
  background: white;
  border-radius: 12px;
  padding: 80px 20px;
  text-align: center;
}

@media (max-width: 768px) {
  .product-content {
    flex-direction: column;

    .product-total {
      align-items: flex-start !important;
    }
  }

  .action-buttons {
    flex-direction: column;

    .el-button {
      width: 100%;
    }
  }
}
</style>
